<template>
  <div class="search-container">
    <!-- 导航栏 -->
    <Navbar />
    
    <div class="search-content">
      <!-- 搜索框 -->
      <div class="search-header">
        <div class="search-input-wrapper">
          <input 
            type="text" 
            v-model="searchQuery" 
            :placeholder="$t('search.placeholder')" 
            @keyup.enter="performSearch"
            ref="searchInput"
          />
          <button @click="performSearch" :disabled="isSearching">
            {{ isSearching ? $t('search.searching') : $t('search.search') }}
          </button>
        </div>
      </div>
      
      <!-- 搜索结果 -->
      <div class="search-results" v-if="showResults">
        <!-- 标签页导航 -->
        <div class="tabs">
          <button 
            v-for="tab in tabs" 
            :key="tab.type"
            @click="switchTab(tab.type)"
            :class="{ active: activeTab === tab.type }"
          >
            {{ tab.name }} {{ tab.count > 0 ? `(${tab.count})` : '' }}
          </button>
        </div>
        
        <!-- 结果内容 -->
        <div class="results-content">
          <!-- 加载状态 -->
          <div v-if="isSearching" class="loading">
            <div class="loading-spinner"></div>
            <span>{{ $t('search.searching') }}</span>
          </div>
          
          <!-- 错误状态 -->
          <div v-else-if="errorMessage" class="error">{{ errorMessage }}</div>
          
          <!-- 空状态 -->
          <div v-else-if="!hasResults" class="empty-state">
            <p>{{ $t('search.noResults') }}</p>
          </div>
          
          <!-- 歌曲结果 -->
          <div v-else-if="activeTab === 'songs'" class="song-results">
            <table class="song-table">
              <thead>
                <tr>
                  <th></th>
                  <th>{{ $t('search.song') }}</th>
                  <th>{{ $t('search.artist') }}</th>
                  <th>{{ $t('search.album') }}</th>
                  <th>{{ $t('search.duration') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr 
                  v-for="(song, index) in searchResults.songs" 
                  :key="song.id"
                  @click="playSong(song)"
                >
                  <td>{{ index + 1 }}</td>
                  <td>{{ song.name }}</td>
                  <td>{{ song.ar ? song.ar.map(a => a.name).join(', ') : song.artists.map(a => a.name).join(', ') }}</td>
                  <td>{{ song.al ? song.al.name : song.album.name }}</td>
                  <td>{{ formatDuration(song.dt || song.duration) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 歌手结果 -->
          <div v-else-if="activeTab === 'artists'" class="artist-results">
            <div class="artist-list">
              <div 
                v-for="artist in searchResults.artists" 
                :key="artist.id"
                class="artist-item"
              >
                <img :src="artist.picUrl || 'https://picsum.photos/id/1005/200/200'" :alt="artist.name" />
                <div class="artist-info">
                  <h4>{{ artist.name }}</h4>
                  <p>{{ artist.musicSize }}{{$t('search.songsCount')}}</p>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 专辑结果 -->
          <div v-else-if="activeTab === 'albums'" class="album-results">
            <div class="album-list">
              <div 
                v-for="album in searchResults.albums" 
                :key="album.id"
                class="album-item"
              >
                <img :src="album.picUrl" :alt="album.name" />
                <div class="album-info">
                  <h4>{{ album.name }}</h4>
                  <p>{{ album.artist.name }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Navbar from '../components/Navbar.vue';

export default {
  name: 'Search',
  components: {
    Navbar
  },
  data() {
    return {
      searchQuery: '',
      searchResults: {
        songs: [],
        artists: [],
        albums: []
      },
      isSearching: false,
      errorMessage: '',
      showResults: false,
      activeTab: 'songs',
      tabs: [
        { type: 'songs', name: this.$t('search.songs'), count: 0 },
        { type: 'artists', name: this.$t('search.artists'), count: 0 },
        { type: 'albums', name: this.$t('search.albums'), count: 0 }
      ]
    };
  },
  computed: {
    // 判断是否有搜索结果
    hasResults() {
      return this.searchResults.songs.length > 0 || 
             this.searchResults.artists.length > 0 || 
             this.searchResults.albums.length > 0;
    }
  },
  methods: {
    // 执行搜索
    async performSearch() {
      if (!this.searchQuery.trim()) return;
      
      try {
        this.isSearching = true;
        this.errorMessage = '';
        
        // 调用搜索API
        const response = await this.$http.get(`/api/search?keywords=${encodeURIComponent(this.searchQuery)}&limit=50`);
        
        // 处理搜索结果
        this.searchResults.songs = response.data.body.result.songs || [];
        this.searchResults.artists = response.data.body.result.artists || [];
        this.searchResults.albums = response.data.body.result.albums || [];
        
        // 更新标签页计数
        this.tabs[0].count = this.searchResults.songs.length;
        this.tabs[1].count = this.searchResults.artists.length;
        this.tabs[2].count = this.searchResults.albums.length;
        
        // 显示搜索结果
        this.showResults = true;
      } catch (error) {
        console.error('搜索失败:', error);
        this.errorMessage = this.$t('search.searchFailed');
      } finally {
        this.isSearching = false;
      }
    },
    
    // 切换标签页
    switchTab(tabType) {
      this.activeTab = tabType;
    },
    
    // 播放歌曲
    async playSong(song) {
      try {
        // 获取歌曲URL
        const response = await this.$http.get(`/api/song_url?id=${song.id}`);
        const songUrl = response.data.body.data[0].url;
        
        if (!songUrl) {
          this.errorMessage = this.$t('search.cannotPlay');
          return;
        }
        
        // 如果有状态管理，可以在这里更新全局播放状态
        if (this.$store) {
          this.$store.actions.playSong(this.$store, song);
        }
        
        // 否则可以通过创建音频元素并播放
        const audio = new Audio(songUrl);
        audio.play();
        
        // 可以在这里添加播放历史记录等逻辑
      } catch (error) {
        console.error('播放歌曲失败:', error);
        alert(this.$t('search.playFailed'));
      }
    },
    
    // 格式化时长
    formatDuration(ms) {
      const minutes = Math.floor(ms / 60000);
      const seconds = Math.floor((ms % 60000) / 1000);
      return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
    }
  },
  mounted() {
    // 组件挂载时自动聚焦搜索框
    this.$nextTick(() => {
      this.$refs.searchInput?.focus();
    });
    
    // 监听路由参数，如果有传递搜索关键词则自动搜索
    if (this.$route.query.keyword) {
      this.searchQuery = this.$route.query.keyword;
      this.performSearch();
    }
  }
};
</script>

<style scoped>
.search-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.search-content {
  flex: 1;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

/* 搜索头部样式 */
.search-header {
  margin-bottom: 30px;
}

.search-input-wrapper {
  display: flex;
  max-width: 600px;
  margin: 0 auto;
}

.search-input-wrapper input {
  flex: 1;
  padding: 12px 20px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s ease;
}

.search-input-wrapper input:focus {
  border-color: #c20c0c;
}

.search-input-wrapper button {
  padding: 12px 24px;
  background-color: #c20c0c;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.search-input-wrapper button:hover:not(:disabled) {
  background-color: #a10a0a;
}

.search-input-wrapper button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 标签页样式 */
.tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.tabs button {
  background: none;
  border: none;
  padding: 8px 16px;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.tabs button:hover {
  color: #c20c0c;
}

.tabs button.active {
  color: #c20c0c;
  border-bottom-color: #c20c0c;
}

/* 结果内容样式 */
.results-content {
  min-height: 400px;
}

/* 加载状态 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.loading span {
  margin-top: 15px;
  color: #999;
}

/* 错误状态 */
.error {
  text-align: center;
  padding: 60px 0;
  color: #c20c0c;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #999;
}

/* 歌曲结果表格 */
.song-table {
  width: 100%;
  border-collapse: collapse;
}

.song-table th, .song-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.song-table th {
  font-weight: bold;
  color: #666;
}

.song-table tbody tr {
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.song-table tbody tr:hover {
  background-color: #f9f9f9;
}

/* 歌手列表 */
.artist-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.artist-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.artist-item:hover {
  background-color: #f9f9f9;
  transform: translateY(-2px);
}

.artist-item img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  margin-bottom: 15px;
  object-fit: cover;
}

.artist-info h4 {
  margin-bottom: 5px;
  font-size: 16px;
  text-align: center;
}

.artist-info p {
  color: #999;
  font-size: 14px;
  text-align: center;
}

/* 专辑列表 */
.album-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.album-item {
  display: flex;
  flex-direction: column;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.album-item:hover {
  background-color: #f9f9f9;
  transform: translateY(-2px);
}

.album-item img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  margin-bottom: 15px;
  border-radius: 4px;
}

.album-info h4 {
  margin-bottom: 5px;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.album-info p {
  color: #999;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-content {
    padding: 15px;
  }
  
  .tabs {
    flex-wrap: wrap;
  }
  
  .song-table {
    font-size: 14px;
  }
  
  .song-table th, .song-table td {
    padding: 8px;
  }
  
  .artist-list,
  .album-list {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
  }
  
  .artist-item img {
    width: 100px;
    height: 100px;
  }
  
  .album-item img {
    height: 150px;
  }
}
</style>